<template>
  <div v-loading="loading" element-loading-text="加载中..."
    style="position: relative;display: flex;flex-direction: column;height: 100%;">
    <div class="top">
      <div class="nav">
        <el-tabs class="demo-tabs" v-model="activeName" @tab-change="tabClick">
          <el-tab-pane :name="0">
            <template #label>
              <span>全部结算单 ({{(OrderStatusQtyData?.waitOrderSettlementQty * 1 + OrderStatusQtyData?.OrderSettlementQty * 1)
                || 0
              }})</span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="1">
            <template #label>
              <span class="custom-tabs-label">
                <span>待结算 ({{ OrderStatusQtyData?.waitOrderSettlementQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane :name="2">
            <template #label>
              <span class="custom-tabs-label">
                <span>已结算 ({{ OrderStatusQtyData?.OrderSettlementQty || 0 }})</span>
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="app-container" style="display: flex;flex-direction: column;height: 100%;">
      <div class="app-container-inner" style="display: flex;flex-direction: column;">
        <div class="search flex-align-center">
          <el-select class="input-item mr5" v-model="dateType" placeholder="日期类型" clearable @change="getOrderListData()">
            <el-option v-for="item in dateTypeSele" :key="item.val" :value="item.val" :label="item.name" />
          </el-select>
          <el-select v-if="dateType" class="input-item mr5" v-model="radio1" placeholder="选择时间" clearable
            @change="radio1 == 1 ? '' : getOrderListData()">
            <el-option v-for="item in timeOptions" :key="item.value" :value="item.value" :label="item.title" />
          </el-select>
          <div class="select-time mr5" v-if="radio1 == 1">
            <el-date-picker v-model="value2" type="daterange" range-separator="~" start-placeholder="开始日期"
              end-placeholder="结束日期" @change="dateChange" value-format="YYYY-MM-DD HH:mm:ss" />
          </div>
          <div class="btn_dropdown">
            <div class="btn_dropdown_type">
              <el-dropdown @command="handleCommand1" trigger="click">
                <span style="font-size: 12px;">
                  {{ orderByTypeList[orderByType - 1].name }}
                  <el-icon>
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-for="i in orderByTypeList" :key="i.value" :command="i.value">{{ i.name
                    }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="btn_dropdown_sort">
              <el-dropdown @command="handleCommand2" trigger="click">
                <span style="margin-left: 5px;font-size: 12px;">
                  {{ orderBySortList[orderBySort - 1].name }}
                  <el-icon>
                    <arrow-down />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item v-for="i in orderBySortList" :key="i.value" :command="i.value">{{ i.name
                    }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          <el-input clearable v-model="input1" placeholder="工单编号" class="input-item mr5"
            @keyup.enter.native="getOrderListData" />
          <el-input clearable v-model="input2" @keyup.enter.native="goodsKeyword" placeholder="商品品牌/名称/型号"
            class="input-item mr5" style="width: 200px;" />
          <el-input clearable v-model="input2" @keyup.enter.native="getOrderListData" placeholder="客户名称/手机号/地址"
            class="input-item mr5" style="width: 200px;" />
          <button class="btn btn-bg1 mr5" @click="getOrderListData">
            <el-icon class="mr5">
              <Search />
            </el-icon>搜索
          </button>
          <button class="btn btn-bg5" @click="clearValue">
            <el-icon class="mr5">
              <RefreshRight />
            </el-icon>重置
          </button>
        </div>
        <div class="table-list" style="flex: 1 ;position: relative;">
          <el-table ref="tableList" height="100%" style="position: absolute;" :border="true" stripe resizable
            :data="tableDataList" @row-dblclick="goDetail">
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <el-table-column type="index" label="序号" fixed="left" min-width="50" />
            <template v-for="item in OrderListTable">
              <el-table-column show-overflow-tooltip :fixed="item.freezeColumn"
                :align="item.code == 'totalPrice' ? 'right' : 'left'" :prop="item.code" :label="item.name"
                v-if="item.showColumn" min-width="140">
                <!--  -->
                <template v-if="item.code == 'code'" #default="scope">
                  <span v-if="scope.row.isRepeatOrder" class="repeat">重</span>
                  <span v-if="scope.row.remindersStatus" class="reminder">催</span>
                  <span class="number" @click="goDetail(scope.row)">{{ scope.row.code }}</span>
                </template>

                <template #default="scope" v-if="item.code == 'module'">
                  <el-tag class="ml-2" type="info">{{ scope.row.module }}</el-tag>
                </template>

                <!--状态 -->
                <template v-if="item.code == 'status'" #default="scope">
                  <el-tag type="warning" v-if="scope.row.status == 1">待派单</el-tag>
                  <el-tag class="ml-2" type="warning" v-if="scope.row.status == 2">待服务商确认</el-tag>
                  <el-tag class="ml-2" type="success" v-if="scope.row.status == 3">处理中</el-tag>
                  <el-tag v-if="scope.row.status == 4">已完成</el-tag>
                  <el-tag type="info" v-if="scope.row.status == 5">已取消</el-tag>
                </template>
                <!--  等级 -->
                <template v-if="item.code == 'level'" v-slot="scope">
                  <span :style="{ color: scope.row.workLevelColor }">{{ scope.row.workLevel }}</span>
                </template>

                <!-- 客户地址 -->
                <template v-if="item.code == 'userAddress'" v-slot="i">
                  <span>{{ i.row.province + ' ' + i.row.city + ' ' + i.row.area + ' ' + i.row.town + ' ' + i.row.address
                  }}</span>
                </template>


                <template v-if="item.code == 'totalPrice'" v-slot="i">
                  <span>￥{{ i.row.totalPrice.toFixed(2) }}</span>
                </template>
                <!--  服务时长 -->
                <template v-if="item.code == 'totalServiceTime'" v-slot="scope">
                  <span :style="{ color: scope.row.serviceTimeColor }">{{ scope.row.serviceTime }}</span>
                </template>
                <!--工单来源  -->
                <template v-if="item.code == 'source'" v-slot="i">
                  <span v-for="item in sources" :key="item.value">
                    <span v-if="i.row.source == item.value">{{ item.title }}</span>
                  </span>

                </template>

              </el-table-column>
            </template>
            <!-- 自定义字段 -->
            <el-table-column show-overflow-tooltip v-for="(key, index) in arrList" :key="index" min-width="140"
              :label="key.name">
              <template v-slot="i">
                <template v-for="item in i.row.fieldVals">
                  {{ item.id == key.id ? item.val : '' }}
                </template>
              </template>
            </el-table-column>
            <!-- 表单设置 -->
            <el-table-column align="center" fixed="right" width="38">
              <template #header>
                <el-tooltip effect="dark" content="列表设置" placement="top-start">
                  <!-- <el-icon @click="tableShowSet">
                      <Tools />
                    </el-icon> -->
                  <el-image @click="tableShowSet"
                    style="display: flex;align-items: center;justify-content: center;width: 16px;"
                    :src="setSvg" :size="20"></el-image>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination ref="pagination" :list_total="totalList" @size-change="getOrderListData"
            @current-change="getOrderListData" />
        </div>
        <!-- <AssignDialog :assignAny="assignAny" :assignDialog="assignDialog" :selecttion="selecttion"
            @assign-dialog="assignDialog = false, isbatch = true" :isbatch="isbatch"
            @update-list="getOrderListData(), selecttion = [], arr = []">
          </AssignDialog> -->
        <!-- 工单导出弹窗 -->
        <!-- 列表设置 -->
        <TableVisibleDialog @update-list="getOrderListData(), getOrderListTableFieldList()" :type="3"
          :dialogTableVisible="dialogTableVisible" @set-table-dialog="dialogTableVisible = $event"></TableVisibleDialog>
      </div>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter } from 'vue-router'
import type { TabsPaneContext } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '../../../components/Pagination/index.vue'
import { getOrderListTableTitleField, getOrderListTableField } from '../../../api/order'
import { getOrderSettlementList, getOrderSettlementStatusQty } from '../../../api/settlement'
import TableVisibleDialog from '../../../components/TableVisibleDialog.vue'
import * as  _ from 'lodash'
import setSvg from "@/assets/order/set.svg"
const tableDataList: any = ref(null)//工单列表数据
const OrderStatusQtyData: any = ref(null)//工单状态数量数据

const activeName: any = ref(0)
const router = useRouter()
const loading: any = ref(false)

const pagination = ref()
const totalList = ref(0)//列表总数量
const dateType = ref(2)
const dateTypeSele = ref([{ name: '报单日期', val: 1 }, { name: '给算日期', val: 2 }, { name: '完工日期', val: 3 }])
let arrList: any = ref([])//自定义字段
const orderByTypeList = ref([{ name: '完工时间', value: 1 }, { name: '结算时间', value: 2 }, { name: '取消时间', value: 3 }])
const orderBySortList = ref([{ name: '升序', value: 1 }, { name: '降序', value: 2 }])
// 搜索栏
const input1 = ref('') // 工单编号
const input2 = ref('') // 搜索客户名称/手机号/地址
const input4 = ref('') // 搜索商品品牌/名称/型号
const tableList = ref() // 表格Dom

// 表头搜索
const value2 = ref('') // 申请时间
const startTime: any = ref(null) // 开始日期
const endTime: any = ref(null) // 结束日期
// 筛选 1-报单时间 3-服务商 4-服务时长
const radio1 = ref(4)
const radio4 = ref(null)

// 报单时间
const timeOptions: any = ref([
  { title: '时间区间', value: 1 },
  { title: '今天', value: 2 },
  { title: '本周', value: 3 },
  { title: '本月', value: 4 },
  { title: '过去三个月', value: 5 },
])

// 工单来源
const sources = ref([
  { title: '平台系统报单', value: 1 },
  { title: '扫码报单', value: 2 },
  { title: '小程序报单', value: 3 },
  { title: 'APP报单', value: 4 },
  { title: 'Excel导入报单', value: 5 },
  { title: '品牌商家建单', value: 6 },
  { title: '平台代商家报单', value: 7 },
  { title: '品牌商家Excel导入', value: 8 },
  { title: '乐开伙伴云', value: 9 }])
// 导航切换
const tabClick = (tab: TabsPaneContext) => {
  activeName.value = Number(tab)
  getOrderListData()
}
// 排序字段类型
const handleCommand1 = (val) => {

  if (orderByType.value != val) {
    orderByType.value = val
    getOrderListData()
  }
}
// 排序类型
const handleCommand2 = (val) => {
  if (orderBySort.value != val) {
    orderBySort.value = val
    getOrderListData()
  }
}
// 重置
const clearValue = () => {
  dateType.value = 2
  radio1.value = 4
  input1.value = ''
  input2.value = ''
  input4.value = ''
  value2.value = ''
  startTime.value = null
  endTime.value = null
  radio4.value = null
  getOrderListData()
}
// 查看工单详细
const goDetail = (val: any) => {
  router.push('/order/odetail/' + val.id + '?isArchive=true')
}

// 报单时间变化时
const dateChange = (val: any) => {
  if (val) {
    startTime.value = val[0]
    endTime.value = val[1]
  } else {
    startTime.value = null
    endTime.value = null
  }
  getOrderListData()
}
const orderBySort = ref(2)//排序类型：1-升序，2-降序,示例值(2)
const orderByType = ref(2)//排序字段类型：1-完工时间，2-结算时间，3-取消时间,示例值(2)
const goodsKeyword = ref('')//	工单商品关键词搜索：商品品牌/名称/型号
//获取工单给算列表
const getOrderListData = _.debounce(async () => {
  let itmeType: any = null
  if (radio1.value) {
    // 筛选条件 时间类型
    itmeType = radio1.value
  }
  let tab: any = null
  if (activeName.value === 0) {//判断是切换为全部工单
    tab = null
  } else {
    tab = activeName.value - 1
  }

  let data: any = {
    "dateType": dateType.value,//报单时间类型
    dateValType: itmeType,//日期参数类型：1-时间区间，2-今天，3-本周，4-本月，5-过去三个月
    goodsKeyword: goodsKeyword.value,//	工单商品关键词搜索：商品品牌/名称/型号
    "limit": pagination.value.size,//每页显示数量
    orderBySort: orderBySort.value,//
    orderByType: orderByType.value,//
    "orderEndTime": endTime.value,//	报单/结算/完工结束日期
    "orderStartTime": startTime.value,//报单/结算/完工开始日期
    "page": pagination.value.current,//当面页码
    "status": tab,//	结算状态：0-待结算，1-已结算
    "userKeyword": input2.value,// 客户关键词：客户名称/手机号/地址
    "workNo": input1.value,//工单单号
  }
  loading.value = true
  await getOrderSettlementList(data).then(res => {
    if (res.data.success) {
      tableDataList.value = res.data.data.rows
      totalList.value = Number(res.data.data.total)
      getOrderStatusQtyData()
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
        offset: 200
      })
    }
    loading.value = false
  })
}, 0)
// 获取工单归档列表状态数量
const getOrderStatusQtyData = async () => {
  await getOrderSettlementStatusQty().then(res => {
    if (res.data.success) {
      OrderStatusQtyData.value = res.data.data.row
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
        offset: 200
      })
    }
  })
}
const getOrderListTableTitleFieldList = async () => {
  await getOrderListTableTitleField().then(res => {
    if (res.data.success) {
      arrList.value = res.data.data.rows
    }

  })
}
// 获取工单列表表头字段
const dialogTableVisible = ref(false)
const OrderListTable: any = ref(null)
const getOrderListTableFieldList = () => {
  getOrderListTableField(2).then(res => {
    if (res) {
      OrderListTable.value = res.data.data.rows
    }
  })
}
// 点击列表设置
const tableShowSet = () => {
  dialogTableVisible.value = true
}

onMounted(() => {
  new Promise(() => {
    getOrderListData()
    getOrderListTableTitleFieldList()
    getOrderListTableFieldList()
  })
})


</script>
  
<style scoped lang="scss">
@import './index';
</style>
  